/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package net.taviscaron.drivenotes.android.activity;

import net.taviscaron.drivenotes.android.Constants;
import net.taviscaron.drivenotes.android.R;
import net.taviscaron.drivenotes.android.service.LoginService;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

/**
 * Login activity
 * @author Andrei Senchuk
 */
public class LoginActivity extends Activity {
    private static final String TAG = "LoginActivity";
    private static final String MAIN_ACTIVITY_ACTION = "net.taviscaron.drivenotes.android.MAIN";
    private EditText loginUsername;
    private EditText loginPassword;
    private Button loginButton;
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.login);
        
        loginUsername = (EditText)findViewById(R.id.loginUsername);
        loginPassword = (EditText)findViewById(R.id.loginPassword);

        loginButton = (Button)findViewById(R.id.loginButton);
        loginButton.setOnClickListener(new OnClickListener() {
	    @Override
	    public void onClick(View view) {
		doLogin();
	    }
	});

    }
    
    private void doLogin() {
	String username = loginUsername.getText().toString().trim();
	if(username.length() == 0) {
	    loginUsername.requestFocus();
	    return;
	}
	
	String password = loginPassword.getText().toString().trim();
	if(password.length() == 0) {
	    loginPassword.requestFocus();
	    return;
	}
	
	LoginService loginService = new LoginService(this);
	
	if(!loginService.isOnline()) {
	    Toast.makeText(this, "You need an internet connection", Toast.LENGTH_SHORT);
	    return;
	}
	
	String token = loginService.login(username, password);
	if(token == null) {
	    Toast.makeText(this, "User with that credentials was not found", Toast.LENGTH_SHORT).show();
	} else {
	    SharedPreferences preferenceManager = PreferenceManager.getDefaultSharedPreferences(this);
	    preferenceManager.edit().putString(Constants.AUTH_KEY_PROP_KEY, token).commit();
	    Log.i(TAG, "token: " + token);
	    
	    Intent intent = new Intent(MAIN_ACTIVITY_ACTION);
	    startActivity(intent);
	    finish();
	}
    }
}
